<template>
  <a-affix :offset-top="top">
    <div class="top_navgation">
      <!-- 顶部导航栏 -->
      <div class="search">
        <a-row class="top_search">
          <a-col :span="12">
            <ul style="display: flex">
              <li @click="doLogin" style="font-size: 11px; font-weight: 200">
                <router-link to="/"
                  ><HomeOutlined
                    style="margin-right: 5px; padding-top: 4px; color: coral"
                  />首页</router-link
                >
              </li>
              <li style="margin-left: 20px; font-size: 11px; font-weight: 200">
                <router-link to="/register"
                  ><SendOutlined
                    style="margin-right: 5px; padding-top: 4px; color: coral"
                  />免费注册</router-link
                >
              </li>
            </ul>
          </a-col>
          <a-col :span="12">
            <ul style="display: flex">
              <li style="margin-left: 20px; font-size: 11px; font-weight: 200">
                <router-link @click="toCart" to="/cart"
                  ><ShoppingCartOutlined
                    style="margin-right: 5px; padding-top: 4px; color: coral"
                  />购物车</router-link
                >
              </li>
              <li style="margin-left: 20px; font-size: 11px; font-weight: 200">
                <a-dropdown>
                  <router-link to="/"
                    ><StarOutlined
                      style="margin-right: 5px; padding-top: 4px; color: coral"
                    />收藏夹 <DownOutlined style="color: coral" />
                  </router-link>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item>
                        <router-link style="font-size: 10px" to="/collectgoods"
                          >收藏的宝贝</router-link
                        >
                      </a-menu-item>
                      <a-menu-item>
                        <a href="javascript:;" style="font-size: 10px"
                          >收藏的店铺</a
                        >
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </li>
              <li
                @click="toPersonal"
                style="margin-left: 20px; font-size: 11px; font-weight: 200"
              >
                <router-link to="/personal"
                  ><DesktopOutlined
                    style="margin-right: 5px; padding-top: 4px; color: coral"
                  />个人中心</router-link
                >
              </li>
            </ul>
          </a-col>
        </a-row>
      </div>
    </div>
  </a-affix>
  <!-- 购物车 -->
  <div
    style="
      background-color: #EBEEF5;
      padding-left: 50px;
      padding-right: 50px;
      padding-top: 20px;
      padding-bottom: 20px;
      height: 100vh;
    "
  >
    <div>
      <a-card :bordered="false" style="height: 95vh">
        <a-row style="height: 40px; display: flex">
          <a-col :span="12" style="display: flex">
            <h2>购物车</h2>
            <h3 style="margin-top: 5px">（全部 {{ total }}）</h3>
          </a-col>
          <a-col :span="12" style="display: flex">
            <span
              style="
                margin-left: 75%;
                margin-right: 15px;
                color: #f40;
                font-size: 20px;
                font-weight: bold;
              "
              >{{ towNumber(totalPrice) }}</span
            >
            <a-button
              @click="toSubmitOrder"
              :disabled="!hasSelected"
              type="primary"
              danger
              >结算</a-button
            >
          </a-col>
        </a-row>
        <a-divider style="height: 2px; background-color: #7cb305" />
        <a-table
          :row-selection="{
            selectedRowKeys: state.selectedRowKeys,
            onChange: onSelectChange,
          }"
          :data-source="data"
          :pagination="false"
          :loading="loading"
          :scroll="{ y: 480 }"
        >
          <a-table-column
            fixed="left"
            key="image"
            title="商品信息"
            data-index="image"
            :ellipsis="true"
          >
            <template #default="{ record }">
              <a-image :width="100" :src="record.image" />
              <router-link @click="toDetail(record.goodsId)" to="">
                <span style="margin-left: 10px">{{ record.name }}</span>
              </router-link>
            </template>
          </a-table-column>
          <a-table-column key="price" title="单价" data-index="price">
            <template #default="{ record }">
              <a-tag color="#f40">
                <template #icon>
                  <PayCircleOutlined />
                </template>
                <span style="font-size: 16px; font-weight: bold">{{
                  towNumber(record.price)
                }}</span>
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column key="number" title="数量" data-index="number">
            <template #default="{ record }">
              <a-input-number
                min="0"
                v-model:value="record.number"
                step="1"
                @blur="handleChange(record.key, record.number)"
              />
            </template>
          </a-table-column>
          <a-table-column
            :ellipsis="true"
            key="totalPrice"
            title="金额"
            data-index="totalPrice"
          >
            <template #default="{ record }">
              <a-tag color="#f40">
                <template #icon>
                  <PayCircleOutlined />
                </template>
                <span style="font-size: 16px; font-weight: bold">{{
                  towNumber(record.totalPrice)
                }}</span>
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column fixed="right" key="id" title="操作">
            <template #default="{ record }">
              <div style="display: flex">
                <div>
                  <a-tooltip color="magenta">
                    <template #title>收藏</template>
                    <a-button @click="collect(record.goodsId)" type="primary" ghost
                      ><HeartOutlined
                    /></a-button>
                  </a-tooltip>
                </div>
                <div style="margin-left: 10px">
                  <a-popconfirm
                    title="删除宝贝？"
                    ok-text="确认"
                    cancel-text="取消"
                    @confirm="remove(record.key)"
                    @cancel="cancel"
                  >
                    <a-button type="primary" ghost danger>
                      <DeleteOutlined href="#" />
                    </a-button>
                  </a-popconfirm>
                </div>
              </div>
            </template>
          </a-table-column>
        </a-table>
      </a-card>
    </div>
  </div>
</template>

<script setup>
import {
  StarOutlined,
  ShoppingCartOutlined,
  DownOutlined,
  DesktopOutlined,
  SendOutlined,
  HomeOutlined,
  DeleteOutlined,
  HeartOutlined,
  PayCircleOutlined,
} from "@ant-design/icons-vue";
import { ref, reactive, computed, onMounted } from "vue";
import { message } from "ant-design-vue";
import { getList, deleteCart, updateById, getOrderId } from "@/api/cart";
import { useUserStore } from "@/stores/user";
import { saveCollectGoods } from "@/api/collectgoods";
import router from "@/router";
const userStore = useUserStore();

const data = ref([]);
const total = ref(0);
const loading = ref(true);
onMounted(() => {
  //获取购物车数据
  setTimeout(() => {
    loading.value = false;
    getLists();
  }, 1500);
});

//获取购物车数据
function getLists() {
  getList(userStore.user.key).then((res) => {
    if (res.code == 200 && res.data != null) {
      data.value = res.data.data;
      total.value = res.data.total;
    }
  });
}

//收藏
const collecGoods = ref({
  userId: null,
  goodsId: null,
});


function collect(id) {
  // 判断用户是否登录
  if (userStore.user.key) {
    // 设置收藏商品的userId和goodsId
    collecGoods.value.userId = userStore.user.key;
    collecGoods.value.goodsId = id;
    // 保存收藏商品
    saveCollectGoods(collecGoods.value).then((res) => {
      if (res.code === 200) {
        // 收藏成功
        message.success("收藏成功！");
      }
    });
  } else {
    // 用户未登录，提示登录
    message.warning("请先登录哦！");
    router.push("/login");
  }
}

//删除
function remove(key) {
  deleteCart(key).then((res) => {
    if (res.code == 200) {
      message.success("删除成功！");
      getLists();
    }
  });
}

//管理员取消删除回调操作
function cancel() {
  message.warning("取消删除！");
}

//跳往商品详情
function toDetail(id) {
  router.push({ name: "Detail", query: { id: id } });
}

//用户移除焦点后重新修改购物车中的数量和总价格
function handleChange(id, number) {
  updateById(id, number).then((res) => {
    if (res.code === 200) {
      getLists();
    }
  });
}

//结算跳往提交订单页
const cartIds = ref([]);
const orderId = ref("");
function toSubmitOrder() {
  // message.success("结算功能暂定于三月中旬开放，请尝试其他功能吧~")
  getOrderId(cartIds.value, userStore.user.key).then((res) => {
    if (res.code === 200) {
      orderId.value = res.data;
      router.push({
        path: "submitorder",
        query: { id: cartIds.value, orderId: orderId.value },
      });
    }
  });
}

//存储批量管理员id
const state = reactive({
  selectedRowKeys: [],
});

//当有一个或多个管理员被选中时触发按钮
const hasSelected = computed(() => {
  return state.selectedRowKeys.length > 0;
});
//当选中行改变时触发
const totalPrice = ref(0.0);
const cartIdList = [];
function onSelectChange(selectedRowKeys, selectedRows) {
  if (selectedRows.length === 0) {
    totalPrice.value = 0.0;
  } else {
    totalPrice.value = 0.0;
    for (let i = 0; i < selectedRows.length; i++) {
      totalPrice.value += selectedRows[i].totalPrice;
      cartIdList.push(selectedRows[i].id);
      //商品id去重
      cartIdList.forEach((item) => {
        if (cartIds.value.indexOf(item) === -1) {
          cartIds.value.push(item);
        }
      });
    }
  }
  state.selectedRowKeys = selectedRowKeys;
}

//展示价格的小数方法
function towNumber(val) {
  return val.toFixed(2);
}
</script>

<style scoped>
.ItemHeader {
  line-height: 28px;
  color: #000;
  letter-spacing: 0;
  font-size: 20px;
  font-family: PingFang SC;
  font-weight: 900;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

a:hover {
  color: red;
}
.top_navgation {
  background-color: #fff;
  color: #303133;
}
.search {
  height: 30px;
  background-color: #f4f4f5;
}
.top_search {
  height: 30px;
  margin-left: 150px;
  margin-right: 150px;
  width: 80%;
  padding-top: 3px;
}
.top_serach {
  height: 100px;
  background-color: #fff;
}

ul {
  list-style-type: none;
}

:deep(.slick-slide) {
  height: 310px;
  background: #364d79;
  overflow: hidden;
  border-radius: 10px;
}
</style>
